package com.design.patterns.list.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Wangzhiwen
 */
public class WeatherSubject implements Subject {

    private Weather weather;

    private final List<Observer> observers;

    public WeatherSubject() {
        observers = new ArrayList<>(16);
    }

    public synchronized void publishWeather(Weather weather) {
        this.weather = weather;
        notifyObservers();
    }

    public synchronized void publishWeather(float temperature, float pressure, float humidity) {
        this.weather = new Weather();
        weather.setTemperature(temperature);
        weather.setPressure(pressure);
        weather.setHumidity(humidity);
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void cleanObservers() {
        observers.clear();
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            if (observer.support(Weather.class)) {
                observer.update(weather);
            }
        }
    }
}
